# -*- coding: utf-8 -*-
from flask import render_template, request, redirect, session
from . import user
from ..funcs import (
    get_md5, db, User, UserInfo
    )



@user.route('/login', methods=['GET', 'POST'])
def login():
    '''验证用户登录'''    

    if request.method == 'POST':
        username = request.values.get('username')
        password = get_md5(request.values.get('password'))

        res = db.query(User, {'username': username, 'password': password}, True)

        if bool(res):
            # 登录成功
            session['user_id'] = res.Id
            return redirect('/')


    return render_template('/user/login.html')

@user.route('/register', methods=['GET', 'POST'])
def register():
    '''注册用户'''

    if request.method == 'POST':
        print('=' * 10, '开始注册')
        username = request.values.get('username')
        password = get_md5(request.values.get('password'))
        email = request.values.get('email')

        # 在数据库中添加用户
        user_dict = {
            'username': username,
            'password': password,
            'email' : email
        }

        res, e = db.addone(User, user_dict)
        if res:
            # 添加用户详细信息

            info_id = db.query(User, user_dict, True).Id
            user_info = {
                'InfoId' : info_id,
                'permission': None,
                'avatar' : None,
                'registDate': None,
                'loginDate' : None,
                'collect' : None,
                'down' : None,
                'noShow' : None,
                'state' : '离线',
                'remarks' : None
            }

            res, e = db.addone(UserInfo, user_info)
            #
            if res:
                # res是添加的状态，为True或False
                # 添加成功，跳转到登录页面
                return redirect('/login')
            else:
                # 如果用户信息没有添加成功就是注册失败，要删除刚刚注册的用户
                pass
            # 如果没有进入登录界面就是添加失败，返回注册界面并附带错误信息
            return render_template('user/register.html', message=e)
    return render_template('user/register.html')

